package com.boer.filedemo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.boer.filedemo.entity.MyFile;
import com.boer.filedemo.service.MyFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/***
 * 下载文件接口
 */
@RestController
public class DownloadController {
    @Autowired
    MyFileService service;

    @GetMapping("/download")
    public String downloadFile(
            @RequestParam("uuid") String uuid,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        //根据uuid从数据库查出文件的路径
        QueryWrapper<MyFile> wrapper = new QueryWrapper<>();
        wrapper.eq("uuid", uuid);
        MyFile myFile = service.getOne(wrapper);
        if (myFile == null) {
            return "不存在此文件";
        }
        String path = myFile.getPath();

        //将下载时提醒的文件名设置为文件的原文件名
        String fileName = myFile.getName();

        if (fileName != null) {
            //设置文件路径
            File file = new File(path);
            if (file.exists()) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
                byte[] buffer = new byte[1024];
                //创建文件流和缓冲流
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    //写入
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    return "下载成功";
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    //关闭流
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return "下载失败";
    }
}

